package com.usefullc.crawler.controller;
import com.google.common.collect.Lists;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.usefullc.common.enums.ValidActionEnum;
import com.usefullc.common.exception.BizException;
import com.usefullc.common.util.JsonUtil;
import com.usefullc.common.util.MimeTypesUtils;
import com.usefullc.common.util.http.HttpNewUtils;
import com.usefullc.common.util.http.RequestRes;
import com.usefullc.common.util.http.ResponseRes;
import com.usefullc.crawler.param.DownloadParam;
import com.usefullc.system.validator.UsefulValid;
import com.usefullc.crawler.domain.OutputTemplate;
import com.usefullc.crawler.param.OutputTemplateParam;
import com.usefullc.crawler.vo.OutputTemplateVo;
import com.usefullc.crawler.query.OutputTemplateQuery;
import com.usefullc.crawler.service.OutputTemplateService;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.system.controller.BaseController;
import com.usefullc.system.controller.WebResultBuilder;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.entity.WebResult;
import com.usefullc.system.param.IdsParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.activation.MimetypesFileTypeMap;
import javax.validation.Valid;

import static com.usefullc.system.controller.WebResultBuilder.successResult;

/**
 * 爬虫输出模板控制类
 * @author: 星空
 * @date: 2022-12-15
 */
@RestController
@RequestMapping("/crawler/outputTemplate/")
@Api( tags="爬虫输出模板")
public class OutputTemplateController extends BaseController {

    @Autowired
    private OutputTemplateService outputTemplateService;

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "爬虫输出模板列表",response = WebResult.class)
    @GetMapping(path = "list",produces = "application/json")
    public WebResult list(@UsefulValid(query = true) OutputTemplateQuery query) {
        Pager<OutputTemplateVo> page = outputTemplateService.findVoByPage(query);
        return WebResultBuilder.successResult(page);
    }

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "爬虫输出模板所有列表", response = WebResult.class)
    @GetMapping(path = "listAll", produces = "application/json")
    public WebResult listAll(@UsefulValid(query = true) OutputTemplateQuery query) {
        List<OutputTemplate> dataList = outputTemplateService.findAll(query);
        return WebResultBuilder.successResult(dataList);
    }


    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "爬虫输出模板详情",response = WebResult.class)
    @GetMapping(path = "detail",produces = "application/json")
    public WebResult detail(@ApiParam(value = "示例ID") @Valid @RequestParam Long id) {
        OutputTemplate outputTemplate = outputTemplateService.findById(id);
        return WebResultBuilder.successResult(outputTemplate);
    }


    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "创建爬虫输出模板", response = WebResult.class)
    @PostMapping(path = "/save", produces = "application/json")
    @UsefulValid
    public WebResult save(@UsefulValid(save=true) @RequestBody OutputTemplateParam param) {
        OutputTemplate outputTemplate = BeanUtils.beanCopy(param, OutputTemplate.class);
        return successResult(outputTemplateService.save(outputTemplate));
    }

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "修改爬虫输出模板", response = WebResult.class)
    @PostMapping(path = "/update", produces = "application/json")
    public WebResult update(@UsefulValid(update=true) @RequestBody OutputTemplateParam param) {
        OutputTemplate oldBean = outputTemplateService.findById(param.getId());
        BeanUtils.beanCopy(param, oldBean);
        return successResult(outputTemplateService.update(oldBean));
    }

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @PostMapping(path = "del",produces = "application/json")
    @ApiOperation(value = "删除爬虫输出模板",response = WebResult.class)
    public WebResult del(@UsefulValid(del=true) @RequestBody IdsParam idParam) {
        outputTemplateService.delete(idParam.getIds());
        return WebResultBuilder.successResult();
    }

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @PostMapping(path = "delByLogic",produces = "application/json")
    @ApiOperation(value = "逻辑删除爬虫输出模板",response = WebResult.class)
    public WebResult delByLogic(@UsefulValid(del=true) @RequestBody IdsParam idParam) {
        outputTemplateService.delete(idParam.getIds());
        return WebResultBuilder.successResult();
    }


    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @PostMapping(path = "outputToDownload",produces = "application/json")
    @ApiOperation(value = "输出下载",response = WebResult.class)
    public WebResult outputToDownload(@UsefulValid @RequestBody DownloadParam param) {
        try{
            RequestRes requestRes = new RequestRes();
            requestRes.setConnectTimeout(15000);
            requestRes.setSocketTimeout(1000*60*3);
            Map<String, String> headerMap = param.getHeaderMap();
            requestRes.setHeaders(headerMap);
            requestRes.setMethod(param.getMethod());
            List<String> urls = param.getUrls();
            List<String> names = param.getNames();
            for (int i = 0; i < urls.size(); i++) {
                String url = urls.get(i);
                requestRes.setUrl(url);
                ResponseRes responseRes = HttpNewUtils.execute(requestRes);
                Integer httpStatus = responseRes.getStatus();
                logger.info("httpStatus={},url={}",httpStatus,url);
                if(responseRes.getStatus() != 200){
                    logger.error("http execute failed,body=",responseRes.getBodyText());
                    continue;
                }
                byte[] body = responseRes.getResult();
                Map<String, String> resHeaderMap = responseRes.getHeaders();
//        String dispostion = resHeaderMap.get("Content-Disposition");
                String contentType = resHeaderMap.get("Content-Type");
                String ext = MimeTypesUtils.getDefaultExt(contentType);

                String localStorePath = param.getLocalStorePath();
                String name = names.get(i);
                String filePath = localStorePath+ File.separator+name + "."+ext;
                File file = new File(filePath);
                FileUtils.forceMkdirParent(file);
                FileUtils.writeByteArrayToFile(file,body);
            }
        }catch (Exception e){
            throw new BizException(e);
        }
        return WebResultBuilder.successResult();
    }


    public static void main(String[] args) {
        DownloadParam downloadParam = new DownloadParam();
        downloadParam.setMethod("");
        downloadParam.setNames(Lists.newArrayList());
//        downloadParam.("");
        downloadParam.setLocalStorePath("");

        List<String> urls = new ArrayList<>();
        urls.add("aa");
        urls.add("bb");
        downloadParam.setUrls(urls);
        String json = JsonUtil.bean2Json(downloadParam);
        System.out.println(json);
    }



}
